<!--
 * @Author: 黄达全
 * @Date: 2024-08-28 17:48:33
 * @LastEditTime: 2024-08-29 18:17:41
-->
<script lang="ts" setup>
import { watch, ref, computed } from "vue"
import { useTable } from "@/hooks/useTable"
import { CategoryTreeVO, CategoryAddForm } from "@/common/type"
import CategoryApi from "@/api/model/category"
import useElementPlus from "@/hooks/useElementPlus"
import drawer from "@/components/drawer.vue"
import selectImage from "@/components/selectImage.vue"

const props = defineProps<{
    categoryId: number
}>()

const canRun = computed(() => props.categoryId ? true : false)


const {
    getData,
    tableData,
    handleSelectionChange,
    tableHeight,
    tableRef,
    total,
    pageSize,
    getDataByPage,
    isAddMode,
    submitHandle,
    initForm,
    formRules,
    del,
    drawerRef,
    editId,
} = useTable<CategoryTreeVO, CategoryAddForm>({
    fetchData: (page) => CategoryApi.select(props.categoryId!, page),
    canRun,
    initForm: {
        name: '',
        status: 1,
        order: 1,
        parentId: 0,
        icon: "",
        imageUrl: ""
    },
    // @ts-ignore
    formRules: {  //ts报错，无法有效解决
        name: [
            { required: true, message: '请输入分类名称', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        status: [
            { required: true, message: '请选择状态', trigger: 'change' }
        ],
        parentId: [
            { required: false, message: '请选择父分类', trigger: 'change' }
        ]
    },
    addItem: (form) => CategoryApi.add(form),
    deleteItem: (ids) => CategoryApi.delete(ids),
    updateItem: (form) => CategoryApi.update(form),
    title: "商品分类"
})

watch(() => props.categoryId, () => {
    console.log(111);

    getData()
    tableData.value = tableData.value.map(item => {
        return {
            ...item,
            children: item.children ? item.children : []
        }
    })
    console.log(tableData.value);

}, {
    immediate: true
})

const { message } = useElementPlus()
const changeStatusHandle = async (e: number, row: CategoryTreeVO) => {
    const { code } = await CategoryApi.update({
        id: row.id,
        status: e,
        name: row.name,
        order: row.order,
        icon: row.icon,
        parentId: row.parentId!
    })
    if (code == 1) {
        message({
            message: "修改状态成功",
            type: "success"
        })
        getData()
    } else {
        message({
            message: "修改状态失败",
            type: "error"
        })
    }
}

const treeData = ref<CategoryTreeVO[]>([])
const getTreeData = async () => {
    const { data } = await CategoryApi.tree()
    treeData.value = data
}

getTreeData()

const openAddGoodsCategoryDrawer = () => {
    isAddMode.value = true
    initForm.parentId = props.categoryId
    initForm.name = ''
    initForm.icon = ''
    initForm.order = 1
    initForm.status = 1
    drawerRef.value.open()
}

const showSelectImage = ref(false)
const openAddGoodsCategoryDrawer2 = (row: CategoryTreeVO) => {
    showSelectImage.value = true
    isAddMode.value = true
    initForm.parentId = row.id
    initForm.name = ''
    initForm.icon = ''
    initForm.imageUrl = ''
    drawerRef.value.open()
}

const editRow = ref<CategoryTreeVO>()
const openEditGoodsCategoryDrawer = (row: CategoryTreeVO) => {
    isAddMode.value = false
    editRow.value = row
    editId.value = row.id
    initForm.parentId = row.parentId!
    initForm.name = row.name
    initForm.icon = row.icon
    initForm.order = row.order
    initForm.status = row.status
    initForm.imageUrl = row.imageUrl
    drawerRef.value.open()
}

const handleChange = (e: number[]) => {
    initForm.parentId = e.reverse()[0]
}

const loadChildren = async (row: CategoryTreeVO, _treeNode: any, resolve: (data: CategoryTreeVO[]) => void) => {
    if (row.children) {
        resolve(row.children)
    } else {
        const { data } = await CategoryApi.select(row.id, 1)
        setTimeout(() => {
            resolve(data.records.map(item=>{
                return {
                    ...item,
                    noAdd:true
                }
            }))
        }, 1000)
    }
}

// 图片上传相关函数
const handleImageSelect = (imageList: any) => {
    if (imageList && imageList.length > 0) {
        initForm.imageUrl = imageList[0].url
    }
}

const submit = () => {
    submitHandle(null)
    tableData.value = []
    getData()
    showSelectImage.value = false
}

</script>

<template>
    <div class="table_form">
        <el-button @click="openAddGoodsCategoryDrawer" type="primary" size="small"
            style="background-color: var(--primary-theme-color);">新增</el-button>
        <el-button @click="del" type="danger" size="small">全选删除</el-button>
    </div>
    <div class="table_container" ref="tableRef">
        <el-table :data="tableData" style="width:99.5%" stripe @selection-change="handleSelectionChange"
            :height="tableHeight" row-key="id" lazy :load="loadChildren" 
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
            <el-table-column type="selection" width="80" align="center" />
            <el-table-column fixed prop="id" label="序号" align="center" />
            <el-table-column prop="imageUrl" label="封面" width="100" align="center">
                <template #default="{ row }">
                    <el-image v-if="row.imageUrl" :src="row.imageUrl" style="width: 40px; height: 40px;" />
                    <div v-else>暂无</div>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="分类名称" width="150" align="center">
                <template #default="{ row }">
                    <div class="category-name">
                        <el-icon v-if="row.icon" class="category-icon">
                            <component :is="`el-icon-${row.icon}`" />
                        </el-icon>
                        {{ row.name }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120" align="center">
                <template #default="{ row }">
                    <el-switch v-model="row.status" :active-value="1" :inactive-value="0"
                        style="--el-switch-on-color: var(--primary-theme-color); --el-switch-off-color: #ccc"
                        @change="changeStatusHandle($event, row)" />
                </template>
            </el-table-column>
            <el-table-column prop="createManagerName" label="创建者" width="140" align="center" />
            <el-table-column prop="lastUpdateManagerName" label="更新者" width="140" align="center" />
            <el-table-column prop="createTime" label="创建时间" width="170" align="center" />
            <el-table-column prop="updateTime" label="更新时间" width="170" align="center" />

            <el-table-column fixed="right" label="操作" align="center" width="200">
                <template #default="{ row }">
                    <el-button type="primary" size="small" @click="openAddGoodsCategoryDrawer2(row)"
                        icon="el-icon-edit" style="background-color: var(--primary-theme-color);" v-if="!row.noAdd&&!row.imageUrl">新增</el-button>
                    <el-button type="warning" size="small" @click="openEditGoodsCategoryDrawer(row)"
                        icon="el-icon-edit">编辑</el-button>
                    <el-button type="danger" size="small" @click="del(row.id)" icon="el-icon-delete">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="pagination">
        <el-pagination size="small" background layout="prev, pager, next" :total="total" :page-size="pageSize"
            @current-change="getDataByPage" />
    </div>
    <drawer ref="drawerRef" :title="isAddMode ? '新增商品分类' : '修改商品分类'" direction="rtl" size="35%" @submit="submit">
        <template #rtl>
            <el-form :model="initForm" :rules="formRules" :label-width="110">
                <el-form-item label="父规格（可选）" prop="parentId">
                    <el-cascader v-model="initForm.parentId" @change="handleChange" :options="treeData" :props="{
                        checkStrictly: true,
                        value: 'id',
                        label: 'name',
                        children: 'children'
                    }" clearable placeholder="请选择父分类（可选）" />
                </el-form-item>


                <el-form-item label="分类名称" prop="name">
                    <el-input v-model="initForm.name" placeholder="请输入商品分类名称"></el-input>
                </el-form-item>
                <el-form-item label="封面" prop="imageUrl" v-if="showSelectImage">
                    <select-image :avatar-url="initForm.imageUrl" :multiple="false" @select-image="handleImageSelect" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch v-model="initForm.status" :active-value="1" :inactive-value="0"
                        style="--el-switch-on-color: var(--primary-theme-color); --el-switch-off-color: #ccc" />
                </el-form-item>
                <el-form-item label="排序">
                    <el-input-number v-model="initForm.order"></el-input-number>
                </el-form-item>
            </el-form>
        </template>
    </drawer>
</template>

<style lang="scss" scoped>
.table_form {
    height: 40px;
    display: flex;
    padding-left: 15px;
    align-items: center;
}

.table_container {
    width: 100%;
    height: calc(100% - 50px - 40px);
    overflow-x: scroll;
}

.pagination {
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
}

:deep(.el-pagination.is-background .el-pager li.is-active) {
    background-color: var(--primary-theme-color) !important;
    color: #FFFFFF;
}

.category-name {
    display: flex;
    align-items: center;
    gap: 8px;
}

.category-icon {
    font-size: 16px;
    color: var(--el-color-primary);
}

:deep(.el-table) {
    .el-table__row {
        &:hover {
            background-color: var(--el-color-primary-light-9);
        }
    }
}
</style>
